package com.example.javamaday.leetcode;

import java.util.Comparator;
import java.util.PriorityQueue;

public class LeetCodeTest1337 {

    public static void main(String[] args) {

    }

    public int[] kWeakestRows(int[][] mat, int k) {
        int[] result = new int[mat.length];
        for (int i = 0; i < mat.length; i++) {
            int num = 0;
            for(int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] == 1) {
                    num++;
                } else {
                    break;
                }
            }
            result[i] = num;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer v1, Integer v2) {
                if (Math.abs(Integer.compare(result[v1], result[v2])) == 1) {
                    return 0 - Integer.valueOf(result[v1]).compareTo(Integer.valueOf(result[v2]));
                } else {
                    return 0 - v1.compareTo(v2);
                }
            }
        });
        for (int i = 0; i < result.length; i++) {
            priorityQueue.offer(i);
            if (priorityQueue.size() > k) {
                priorityQueue.poll();
            }
        }

        int length = priorityQueue.size();
        int[] resultFinish = new int[length];
        for (int i = 0; i < length; i++) {
            resultFinish[i] = priorityQueue.poll();
        }

        int temp;
        for (int i = 0; i < length / 2; i++) {
            temp = resultFinish[i];
            resultFinish[i] = resultFinish[length - i - 1];
            resultFinish[length - i - 1] = temp;
        }

        return resultFinish;
    }
}
